import {UserInfo} from "../types/CommonTypes.ts";

export type CacheData<T>={
    data: T,
    //过期时间
    expire: number,
    //初始设置时间
    startTime?: number,
}
export const setDataToLocal = (key:string, cacheData: CacheData<unknown>) => {
    cacheData.startTime = Date.now();
    localStorage.setItem(key, JSON.stringify(cacheData));
};
export const getDataFromLocal = <T>(key:string):T|null => {
    const item = localStorage.getItem(key);
    if (!item) {
        return null;
    }
    const cacheData: CacheData<T> = JSON.parse(item);
    if (!cacheData) {
        return null;
    }
    //惰性过期
    const expire = cacheData.expire;
    let startTime = cacheData.startTime;
    if (!startTime) {
        startTime = Date.now();
        cacheData.startTime = startTime;
    }
    const now = Date.now();
    if ((now-startTime)/1000 > expire) {
        removeDataFromLocal(key);
        return null;
    }
    return cacheData.data;
};
export const removeDataFromLocal = (key:string) => {
    localStorage.removeItem(key);
};

export const setUserTokenToLocal = (token: string, expire:number) => {
    const cacheData: CacheData<string> = {
        data: token,
        expire,
    }
    setDataToLocal("userToken", cacheData);
}
export const getUserTokenFromLocal = () => {
    return getDataFromLocal<string>("userToken");
}
export const setUserInfoToLocal = (userInfo: UserInfo, expire:number) => {
    const cacheData: CacheData<UserInfo> = {
        data: userInfo,
        expire,
    }
    setDataToLocal("userInfo", cacheData);
}
export const getUserInfoFromLocal = (): UserInfo|null  => {
    return getDataFromLocal<UserInfo>("userInfo");
}

